import React from 'react';
import ReactDOM from 'react-dom';
import mirror, {actions, connect} from 'mirrorx';
import { Button, List } from 'antd-mobile';
import RowSelect from '../../../component/Item/Select';
import RowDate from '../../../component/Item/DatePicker';
const Item = List.Item;
import CartRow from './cart-row';

class App extends React.Component { 
	constructor(props) {
		super(props);
		const Lang = window.LangMessage ||{};
		this.state = {
			consignee: 'san',
			goodsList: [
				{
					id: '1',
					title: Lang.mobile_phone || '手机',
					num: 1,
					price:  5000,
					checked: false
				},
				{
					id: '2',
					title: Lang.plane_ticket || '机票',
					num: 1,
					price:  2000,
					checked: false
				},
				{
					id: '3',
					title: Lang.clothes || '衣服',
					num: 1,
					price:  500,
					checked: false
				},
				{
					id: '4',
					title: Lang.fresh_food || '生鲜食品',
					num: 1,
					price:  200,
					checked: false
				},
				{
					id: '5',
					title: Lang.flat_panel_TV || '平板电视',
					num: 1,
					price:  4000,
					checked: false
				}
			],
			consigneeData: {
				san: {
					name: Lang.web_zhangsan || "张三",
					gender: Lang.gender_male || "男",
					birthday: new Date("1978/1/1").getTime(),
					// birthday: "1978-01-01",
					phone: "13812345678",
					address: Lang.order_address || '上海市北京东路130号',
				},
				si: {
					name: Lang.web_lisi || "李四",
					gender: Lang.gender_male || "男",
					birthday: new Date("1978/1/1").getTime(),
					// birthday: "1988-12-01",
					phone: "13987654321",
					address: Lang.order_address || '上海市北京东路130号',
				}
			},
			goodCateList: [],// 推荐商品所需参数
			RecommendGoods: [] // 推荐商品列表
		}
	}

	componentDidMount(){
		// 下单页
    }
   
	getConsignee = () => {
		const Lang = window.LangMessage ||{};
		const list = [
			{
				label: Lang.web_zhangsan || "张三",
				value: "san",
			},{
				label: Lang.web_lisi || "李四",
				value: "si",
			}
		];
		return list;
	}

	onChange = (obj) => {
		const {goodCateList} = this.state;
		this.setState(obj, ()=>{
			this.requestRecommend(goodCateList);
		});
	}

	onChangeBirthday = (obj) => {
		const {consignee} = this.state;
		Object.assign(this.state.consigneeData[consignee], obj)
		this.setState({consigneeData: this.state.consigneeData})
	}

	onChangedAction = (event, rowItem) => {
		this.state.RecommendGoods.map((item, index)=>{
			if(item.goodCode == rowItem.goodCode){
				item.checked = event.target.checked;
			}
			return item;
		})
		this.setState({RecommendGoods: this.state.RecommendGoods})
	}

	callbackChecked = (checked, rowItem) => {
		const {goodCateList} = this.state;
		if(goodCateList.indexOf(rowItem.title) < 0 && checked ){
			goodCateList.push(rowItem.title)
		}
		if(goodCateList.indexOf(rowItem.title) > -1 && !checked ){
			goodCateList.splice(goodCateList.indexOf(rowItem.title), 1)
		}
		this.state.goodsList.map((item, index)=>{
			if(item.id == rowItem.id){
				item.checked = checked;
			}
			return item;
		})
		this.setState({goodsList: this.state.goodsList})
		this.requestRecommend(goodCateList);
	}

	subTotal = () => {
		let total = 0;
		this.state.goodsList.forEach((item, index)=>{
			if(item.checked){
				total += item.price
			}
		})
		this.state.RecommendGoods.forEach((item, index)=>{
			if(item.checked){
				total += Number(item.premium)
			}
		})
		return total;
	}

	handleRecommend = () => {
		this.requestRecommend();
	}

	requestRecommend = (goodCateList) => {
		const {consignee, consigneeData} = this.state;
		T.fetch({ 
            url:'/market/intelligentRecommendation.json',
            loading:true,
            data:{
				"customerName": consigneeData[consignee].name,
				"gender": 'MALE',//consigneeData[consignee].gender == (Lang.gender_male || "男") ? 'MALE':'FMAIL',
				"birthday": consigneeData[consignee].birthday,
				"address":  consigneeData[consignee].address,
				"phone": consigneeData[consignee].phone,
				"goodCate": goodCateList,
			}
        }).then((res)=>{
            if(res.success){
				console.log("res", res)
				let items = res.value.items || [];
				items.forEach((item, index)=>{
					item.checked = false;
				})
				this.setState({RecommendGoods: items})
            }
        })
	}

	//结算
	handleSettlement = () => {
		const {consignee, consigneeData, goodsList, RecommendGoods} = this.state;
		let param = {
			applicantName: consigneeData[consignee].name,
			applicantGender: "MALE",
			applicantCertType: "SHENFENZHENG",
			applicantCertNo: "440306199210260079",
			applicantBirthday: consigneeData[consignee].birthday,
			applicantMobile: consigneeData[consignee].phone,
			ensurePersons: [],
			orderType: "FAMILY",
		}
		this.state.RecommendGoods.forEach((item, index)=>{
			if(item.checked){
				param.ensurePersons.push({
					relation: "SELF",
					insurantName: consigneeData[consignee].name,
					insurantGender: "MALE",
					insurantCertType: "SHENFENZHENG",
					insurantCertNo: "440306199210260079",
					insurantBirthday: consigneeData[consignee].birthday,
					insurantMobile: consigneeData[consignee].phone,
					insurantPremium: item.premium,
					ensurePlanId: item.goodPlanId
				})
			}
		})
		let goods = [];
		let total = 0;
		goodsList.forEach((item, index)=>{
			if(item.checked){
				goods.push({
					title: item.title,
					price: item.price
				})
			}
		})
		RecommendGoods.forEach((item, index)=>{
			if(item.checked){
				goods.push({
					title: item.title,
					price: item.premium
				})
				total+=Number(item.premium)
			}
		})
		if(param.ensurePersons.length == 0){
			T.showInfo(window.LangMessage.choose_insurance_goods || '请选择保险商品')
			return;
		}
		this.requestSubmit(param, total)
		sessionStorage.setItem("goods",  JSON.stringify(goods));
		console.log('param', param)
	}

	requestSubmit = (param, total) => {
        T.fetch({ 
            url:'/order/submit.json',
            loading:true,
            data:param
        }).then((res)=>{
            if(res.success){
				console.log("res", res)
				actions.routing.push({
                    pathname: 'pay2',
                    search: `?id=${res.value.orderNo}&total=${total}`
                })
            }
        })
	}
	
	onChangedAll = (event) => {
		const {goodCateList} = this.state;
		this.state.goodsList.map((item, index)=>{
			item.checked = event.target.checked;
			if(event.target.checked){
				goodCateList.push(item.title)
			}else{
				goodCateList.splice(0, goodCateList.length)
			}
			return item;
		})
		this.setState({goodsList: this.state.goodsList})
		this.requestRecommend(goodCateList);
	}

	render() {
		const {consignee, consigneeData, goodsList, RecommendGoods} = this.state;
		const Lang = window.LangMessage ||{};
		return (
            <div className="order">
				<div className="order-conent">
					<RowSelect label={Lang.consignee || "收货人"} name="consignee" value={this.state.consignee} data={this.getConsignee()} callback={this.onChange} />
					<div style={{display:consignee=='san'?'block':'none'}}> 
						<List>
							<Item wrap extra={consigneeData[consignee]&&consigneeData[consignee].gender}>{Lang.gender || "性别"}</Item>
							{/* <RowDate label={Lang.date_of_birth || "出生日期"} name="birthday" value={consigneeData[consignee]&&consigneeData[consignee].birthday} callback={this.onChangeBirthday} /> */}
							<Item wrap extra={T.formatDate('yyyy-MM-dd' ,consigneeData[consignee]&&consigneeData[consignee].birthday)}>{Lang.date_of_birth || "出生日期"}</Item>
							<Item wrap extra={consigneeData[consignee]&&consigneeData[consignee].phone}>{Lang.phone || "联系电话"}</Item>
							<Item wrap extra={consigneeData[consignee]&&consigneeData[consignee].address}>{Lang.address || "收货地址"}</Item>
						</List>
					</div>
					<h2 className="f34">{Lang.goods_list || "商品列表"}</h2>
					<table className="order-goods-list">
						<thead>
							<tr>
								<th><label><input type="checkbox" onChange={this.onChangedAll} /></label></th>
								<th>{Lang.web_goods || "商品"}</th>
								<th>{Lang.web_count || "数量"}</th>
								<th>${Lang.price || "价格"}</th>
							</tr>
						</thead>
						<tbody>
							{
								goodsList.map((item, index)=>{
									return (
										<CartRow 
											key={item.id} 
											rowItem={item} 
											callbackChecked={this.callbackChecked} />
									)
								})
							}
						</tbody>
					</table>
					{/* <div className="clearfix">
						<Button className="fr mr40" type="ghost" inline onClick={this.handleRecommend}>{Lang.recommend || "推荐"}</Button>
					</div> */}
					<div className="recommend" style={{display: RecommendGoods.length!=0?'block':'none'}}>
						<h2 className="f34">{Lang.recommend || "推荐"}</h2>
						<ul>
							{
								RecommendGoods.map((item, index)=>{
									return (<li key={index}>
										<div>
											<label><input type="checkbox" checked={item.checked} onChange={(e)=>this.onChangedAction(e,item)} /></label>
										</div>
										<div>
											<p>{item.title}</p>
											<p>{`$${item.premium}`}</p>
											<p>{item.goodDesc}</p>
											<p>{Lang.Please_see__details || "请看详情"}</p>
										</div>
										<div className="img-div"><img src={"/ajax/file/downLoadFile/"+item.imageUrlCode+".file"} style={{'height':'100%'}} className="mid" /></div>
									</li>)
								})
							}
						</ul>
					</div>
				</div>
				<div className="footer">
                    <div className="footer-left">
                        <a className="f38 fc6 tac color-price">&nbsp;&nbsp;<span className="f30"></span><span id="totalMoney">${this.subTotal()}</span></a>
                    </div>
                    <div className="footer-right">
                        <a href="javascript:;"  className="f32 fcw diy_background" onClick={this.handleSettlement}>{Lang.web_settlement || "结算"}</a>
                    </div>
                </div>
            </div>
        )
	}
}

export default App;